'use strict'


//创建ue全局变量
    var ue;
//定义当前页面锚点
    var hash = window.location.hash;
//定义url
var url = '';
// SPA配置
// 依赖ngRoute模块
    var Publish = angular.module('Publish', ['ngRoute', 'NetworkRequest']);
// 需要对路由模块进行配置，使其正常工作
    Publish.config(['$routeProvider', function ($routeProvider) {

        $routeProvider.when('/article', {
                // 相对于当前app页面
                templateUrl: 'article/publish_article.html',//视图模型
             })
            .when('/video', {
                templateUrl: 'video/publish_vid.html',
                controller:'videoPublishController'

            })
            .when('/topic', {
                templateUrl: 'topic/publish_topic.html',

            })
            .otherwise({
                redirectTo: 'article/publish_article.html'
            });

    }]);
//		发布页面控制器
    Publish.controller('publishController', ['$scope', function ($scope) {
        // console.log($scope.url)
        if (hash == "#/article") {
            url = $scope.url.base +  $scope.url.addArticle
            $scope.title = "发表文章";
            $scope.publicBtn = "发表文章"

            // 实例化编辑器// 传入自定义参数
            ue = UE.getEditor('container', {
                toolbars: [[
                    'fullscreen', 'source', '|', 'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                    'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'simpleupload', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
                    'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
                    'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
                    'print', 'preview', 'searchreplace', 'drafts', 'help'
                ]],
                // 自动长高
                autoHeightEnabled: true,
                // 保持toolbar的位置不动
                autoFloatEnabled: true,
                // 自动保存
                enableAutoSave: false,

            });
            //修改图片上传的action
            UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
            UE.Editor.prototype.getActionUrl = function(action) {
                //判断路径   这里是config.json 中设置执行上传的action名称
                if (action == 'uploadimage' ) {
                    return '/api/v1/admin/uploadimage';
                }else {
                    return this._bkGetActionUrl.call(this, action);
                }
            }

            // 设置和读取编辑器的内容
            // var ue = UE.getContent();
            // console.log(ue)
            //对编辑器的操作最好在编辑器ready之后再做
            ue.ready(function () {
                //设置编辑器的内容
                ue.setContent('');
                //获取html内容，返回: <p>hello</p>
                var html = ue.getContent();
                //获取纯文本内容，返回: hello
                // var txt = ue.getContentTxt();
                // console.log(html)
            });
//显示文章类型
            $(".articleType").css("display", "block")
        }

        else if (hash == "#/video") {
            //  发布视频
            url = $scope.url.base + $scope.url.addVideo;
            $scope.title = "发布视频";
            $scope.publicBtn = "发布视频"
        } else {
            url = $scope.url.base + $scope.url.addTopic
            $scope.title = "发布话题";
            $scope.publicBtn = "发布话题"

        }



// 发布按钮点击，提交数据
    $(function () {
        console.log(url)
        // 判断类型 验证表单  创建不同的表单
        $('.publicBtn').on('click', function () {
            //返回携带数据的form
            // var form = formType(hash)

            formType(hash)


        })


    })

    function formType(hash) {
        //获取文字主题
        var title = $("#title").val()
        if (hash == "#/article") {
            // 修改ajax中的url
            // url = "/api/v1/admin/article/add"
            // 获取文章类型
            var articleType = $("#articleType").val()

            // 获取文章主题图片URL
            // var articleCover = $("#articleCover").val()
            // 获取文章主题内容
            var articleContent = getContent()
            //获取图片内容
            // var articleImg =  $('img').src
            // console.log(articleImg)


            // 开始验证
            if (hasTitle(title) && hasPic(articleCover) && hasContent(articleContent)) {
                //验证通过 创建表单信息
                // var form = new FormData($('#form_article'));
                var formData = new FormData();
                console.log(document.getElementById("articleCover").files[0])
                formData.append("image", document.getElementById("articleCover").files[0])

                console.log(`文章标题：${title}`)
                console.log(`文章类型：${articleType}`)
                // console.log(`文章主题图片路径：${articleCover}`)
                console.log(`文章主题内容：${articleContent}`)
                // 进行图片上传以及添加文章请求
                $scope.ajaxForm($scope.url.imageUpload, formData, function (res) {
                    var articleCover = res.data.url
                    console.log("文章封面url:" + res.data.url);
                    //添加文章请求
                            $scope.addArticle(title , articleType, articleCover, articleContent, function(res){
                                if(res && res.status==200){
                                    console.log(res)
                                    alert("添加文章成功")
                                    window.location.href = $scope.router.returnArticle

                                }else if(res.status == 403 ){
                                    alert("加载失败,请先登录！");
                                    window.location.href = $scope.router.returnLogin
                                }else{
                                    //40
                                    alert("请检查添加图片是否正确！")

                                }

                            }, function (error) {
                                console.log(error)
                            })

                },function (error) {
                    console.log(error)
                })


            } else if (!hasTitle(title)) {
                $('.tips p').html('文章主题不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false
            } else if (!hasPic(articleCover)) {
                $('.tips p').html('文章主题图片不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false

            } else {
                $('.tips p').html('文章内容不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false

            }


        } else if (hash == "#/video") {
            // 获取视频路径URL
            var video = $("#videoUrl").val()

            var formData = new FormData();
            console.log(document.getElementById("videoUrl").files[0])
            formData.append("video", document.getElementById("videoUrl").files[0])
            console.log(`视频主题：${title}`)
            console.log(`视频：${video}`)


            if (hasTitle(title) && hasVideo(video)) {
                //验证通过 创建表单信息

                // 请求添加视频
                // 进行图片上传以及添加话题请求
                $scope.ajaxForm($scope.url.videoUpload, formData, function (res) {
                    var articleCover = res.data.url
                    console.log("视频url:" + res.data.videoUrl);
                    console.log("视频图片url:" + res.data.imageUrl);
                    var videoUrl = res.data.videoUrl
                    var imageUrl = res.data.imageUrl


                    //添加话题请求
                    $scope.addVideo(title , videoUrl, imageUrl, function(res){
                        if(res && res.status==200){
                            console.log(res)
                            alert("添加视频成功")
                            window.location.href = $scope.router.returnVideo

                        }else if(res.status == 403 ){
                            alert("加载失败,请先登录！");
                            window.location.href = $scope.router.returnLogin
                        }else{
                            //40
                            alert("请检查添加图片是否正确！")

                        }

                    }, function (error) {
                        console.log(error)
                    })

                },function (error) {
                    console.log(error)
                })


            } else if (!hasTitle(title)) {
                $('.tips p').html('视频主题不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false
            } else {
                $('.tips p').html('视频不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false

            }

        } else {
            // 发布话题

            // 获取文章主题图片URL
            var articleCover = $("#articleCover").val()
            // 获取话题内容
            var articleContent = $("#articleContent").val()

            console.log(`话题主题：${title}`)
            console.log(`话题图片路径：${articleCover}`)
            console.log(`话题内容：${articleContent}`)
            // 开始验证
            if ((hasTitle(title) && hasPic(articleCover) && hasContent(articleContent))) {
                //验证通过 创建表单信息
                var formData = new FormData();
                formData.append("image", document.getElementById("articleCover").files[0])



                // 进行图片上传以及添加话题请求
                $scope.ajaxForm($scope.url.imageUpload, formData, function (res) {
                    var articleCover = res.data.url
                    console.log("话题封面url:" + res.data.url);
                    //添加话题请求
                    $scope.addTopic(title , articleCover, articleContent, function(res){
                        if(res && res.status==200){
                            console.log(res)
                            alert("添加话题成功")
                            window.location.href = $scope.router.returnTopic

                        }else if(res.status == 403 ){
                            alert("加载失败,请先登录！");
                            window.location.href = $scope.router.returnLogin
                        }else{
                            //40
                            alert("请检查添加图片是否正确！")

                        }

                    }, function (error) {
                        console.log(error)
                    })

                },function (error) {
                    console.log(error)
                })


            } else if (!hasTitle(title)) {
                $('.tips p').html('话题主题不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false
            } else if (!hasPic(articleCover)) {
                $('.tips p').html('话题主题图片不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false

            } else if (!hasContent(articleContent)) {
                $('.tips p').html('话题内容不能为空！').css('display', 'block');
                $('.tips').fadeIn(1000).delay(1500).fadeOut(1000);
                return false

            }
        }
    }

    }])

// 发布视频控制器
     Publish.controller('videoPublishController', ['$scope', function ($scope){
         // $scope.video = document.getElementById('videoShow').src
         // console.log( $scope.video)
         $scope.deleVideo = function () {
             // alert(1)
             $('#videoBgc').css("display", "block")
             $(".video .addVideo ").css("display", "block")
             $(".video .deleVideo ").css("display", "none")
             $("#videoShow").css("display", "none")
             $('#videoShow').attr('src', "");
         }
     }])
//验证主题
    function hasTitle(title) {
        if (title == "") {
            return false
        }
        return true
    }

//验证图片
    function hasPic(articleCover) {
        if (articleCover == "") {
            return false
        }
        return true
    }

//验证视频
    function hasVideo(video) {
        if (video == "") {
            return false
        }
        return true
    }

// 验证文章正文
    function hasContent(articleContent) {
        if (articleContent == "") {
            return false
        }
        return true
    }


//获取富文本编辑器的内容
    function getContent() {
        var txt = ue.getContent()
        console.log(txt)
        return txt
    }

//预览图片
    function previewImage(file) {
        console.log(file)
        var MAXWIDTH = 200;
        var MAXHEIGHT = 200;
        //var div = document.getElementById('preview');
        if (file.files && file.files[0]) {
            //div.innerHTML = '<img id=imghead>';
            var img = document.getElementById('imghead');
            img.onload = function () {
                var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                img.width = rect.width;
                img.height = rect.height;
                img.style.marginLeft = rect.left + 'px';
                img.style.marginTop = rect.top + 'px';
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                // console.log(evt.target.result)
                img.src = evt.target.result;
                // console.log(img.src)
            }
            //如果reader读取成功，则调用reader.onload事件
              reader.readAsDataURL(file.files[0]);

            // uploadPhoto();


        } else {
            var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
            file.select();
            var src = document.selection.createRange().text;
            // div.innerHTML = '<img id=imghead>';
            var img = document.getElementById('imghead');
            img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
            var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
            status = ('rect:' + rect.top + ',' + rect.left + ',' + rect.width + ',' + rect.height);
            // div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;margin-left:"+rect.left+"px;"+sFilter+src+"\"'></div>";
            // uploadPhoto();


        }


    }

//设置预览图片大小
    function clacImgZoomParam(maxWidth, maxHeight, width, height) {
        var param = {
            top: 0,
            left: 0,
            width: width,
            height: height
        };
        if (width > maxWidth || height > maxHeight) {
            rateWidth = width / maxWidth;
            rateHeight = height / maxHeight;


            if (rateWidth > rateHeight) {
                param.width = maxWidth;
                param.height = Math.round(height / rateWidth);
            } else {
                param.width = Math.round(width / rateHeight);
                param.height = maxHeight;
            }
        }


        param.left = Math.round((maxWidth - param.width) / 2);
        param.top = Math.round((maxHeight - param.height) / 2);
        return param;
    }

//获取视频路径并显示播放
    function previewVideo(file) {
        // alert(1)
        var file = file.files[0];
        var str = "video"


        //判断文件类型
        // 防止用户点击取消
        if (file.type) {
            if (file.type.indexOf(str) == 0) {
                //隐藏背景图片和添加视频提示
                $('#videoBgc').css("display", "none")
                $(".video .addVideo ").css("display", "none")
                $(".video .deleVideo ").css("display", "block")
                $("#videoShow").css("display", "block")
                var oFReader = new FileReader();
                oFReader.readAsDataURL(file);
                oFReader.onloadend = function (e) {
                    var src = e.target.result;
                    $('#videoShow').attr('src', src);
                }


            } else {
                $(".video .addVideo ").css({
                    'color': 'red',
                    "padding-left": '5px',
                }).text("只能选择音频文件，点击重新选择！")

            }
        }


    }


    function func(file) {
        console.log(file.files[0]['path'])
        console.log($("#videoUrl").val())
    }


